package com.baijiayun.liveuibase.toolbox.responder

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.ListView
import android.widget.TextView
import com.baijiahulian.common.cropperv2.uikit.CircleColorView
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.livecore.models.LPGroupItem
import com.baijiayun.livecore.models.LPUserModel
import com.baijiayun.livecore.models.roomresponse.LPResRoomGroupInfoModel
import com.baijiayun.livecore.utils.CommonUtils
import com.baijiayun.livecore.utils.LPRxUtils
import com.baijiayun.liveuibase.R
import com.baijiayun.liveuibase.base.BaseAdapter
import com.baijiayun.liveuibase.base.BaseTitleWindow
import com.baijiayun.liveuibase.base.BaseWindow
import com.baijiayun.liveuibase.base.ViewHolder
import com.baijiayun.liveuibase.toolbox.responder.model.ResponderRecordModel
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

class ResponderWindow(context: Context) : BaseWindow(context) {
    private val responderAdapter by lazy {
        ResponderAdapter(context)
    }

    private val responderRecordList by lazy {
        view.findViewById<ListView>(R.id.responder_record_listview)
    }

    private var countdownTime: Int = 0
    private var responderStatus: ResponderStatus? = ResponderStatus.TO_PUBLISH
    private var preResponderStatus: ResponderStatus? = ResponderStatus.TO_PUBLISH
    private var lpUserModel: LPUserModel? = null
    private var finishTimerDisposable: Disposable? = null
    private lateinit var groupCircleColorView: CircleColorView


    override fun onCreateView(context: Context?): View {
        val view = View.inflate(context, R.layout.uibase_window_responder, null)
        view.background = ThemeDataUtil.getCommonWindowBg(context)
        groupCircleColorView = view.findViewById(R.id.view_group_color)
        allowTouch = false
        return view
    }

    init {
        initView()
        subscribe()
    }

    private fun initView() {
        addClickAction()
        responderRecordList.dividerHeight = 0
        responderRecordList.adapter = responderAdapter
        resetCountdownStatus()
    }

    private fun subscribe() {
        routerListener.getLiveRoom()?.run {
            compositeDisposable.addAll(toolBoxVM.observableOfAnswerRacerEnd
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        if (it.isRevoke) {
                            changeStatus(ResponderStatus.TO_PUBLISH, "")
                        } else {
                            if (it.winner != null) {
                                changeStatus(ResponderStatus.PUBLISHED, it.winner.getName(), it.winner)
                            } else {
                                changeStatus(ResponderStatus.PUBLISHED, "")
                            }
                        }
                    })
        }
    }

    private fun addClickAction() {
        `$`.id(R.id.responder_plus_btn)
                .clicked {
                    updateCountdownText(true)
                }
                .id(R.id.responder_reduce_btn)
                .clicked {
                    updateCountdownText(false)
                }
                .id(R.id.responder_publish_btn)
                .clicked {
                    routerListener.getLiveRoom()?.run {
                        toolBoxVM.requestAnswerRacerStart(countdownTime)
                    }
                }
                .id(R.id.responder_revoke_btn)
                .clicked {
                    routerListener.getLiveRoom()?.run {
                        toolBoxVM.requestAnswerRacerEnd(true)
                    }
                }
                .id(R.id.responder_reset_btn)
                .clicked {
                    resetCountdownStatus()
                }
                .id(R.id.responder_revoke_btn)
                .clicked {
                    routerListener.getLiveRoom()?.run {
                        toolBoxVM.requestAnswerRacerEnd(true)
                    }
                }
                .id(R.id.responder_finish_btn)
                .clicked {
                    routerListener.getLiveRoom()?.run {
                        toolBoxVM.requestAnswerRacerEnd(false)
                    }
                }
                .id(R.id.responder_edit_again_btn)
                .clicked {
                    changeStatus(ResponderStatus.TO_PUBLISH, "")
                }
                .id(R.id.responder_record_tv)
                .clicked {
                    if (responderStatus == ResponderStatus.RECORD) {
                        if (preResponderStatus == ResponderStatus.PUBLISHED && lpUserModel != null) {
                            changeStatus(ResponderStatus.PUBLISHED, lpUserModel!!.name, lpUserModel, true)
                        } else {
                            changeStatus(preResponderStatus, "")
                        }
                    } else {
                        preResponderStatus = responderStatus
                        changeStatus(ResponderStatus.RECORD, "")
                    }
                }
                .id(R.id.base_window_title_close)
                .clicked {
                    routerListener.getLiveRoom()?.toolBoxVM?.requestComponentDestroy(LPConstants.ComponentType.Responder)
                    if (responderStatus == ResponderStatus.PUBLISHING) {
                        routerListener.getLiveRoom()?.toolBoxVM?.requestAnswerRacerEnd(true)
                    }
                }
                .id(R.id.responder_invite_answer_btn)
                .clicked {
                    lpUserModel?.let { it1 -> routerListener.inviteToSpeak(it1) }
                }
    }

    private fun resetCountdownStatus() {
        countdownTime = 0
        `$`.id(R.id.responder_countdown_time_tv).text(countdownTime.toString())
    }

    private fun updateCountdownText(increase: Boolean) {
        if (increase) {
            countdownTime++
        } else {
            countdownTime--
        }
        if (countdownTime >= 10) {
            countdownTime = 10
        } else if (countdownTime <= 0) {
            countdownTime = 0
        }
        `$`.id(R.id.responder_countdown_time_tv).text(countdownTime.toString())
    }

    fun changeStatus(responderStatus: ResponderStatus?, winner: String?) {
        changeStatus(responderStatus, winner, null)
    }

    private fun changeStatus(responderStatus: ResponderStatus?, winner: String?, userModel: LPUserModel?) {
        changeStatus(responderStatus, winner, userModel, false)
    }

    private fun changeStatus(responderStatus: ResponderStatus?, winner: String?, userModel: LPUserModel?, isRecordBack: Boolean) {
        this.responderStatus = responderStatus
        when (responderStatus) {
            ResponderStatus.TO_PUBLISH -> {
                `$`.id(R.id.responder_to_publish_ll)
                        .visible()
                        .id(R.id.responder_publishing_rl)
                        .visibility(View.GONE)
                        .id(R.id.responder_to_publish_content_ll)
                        .visible()
                        .id(R.id.responder_publish_success)
                        .visibility(View.GONE)
                        .id(R.id.ll_responder_winner_container)
                        .visibility(View.GONE)
                        .id(R.id.responder_record_listview)
                        .visibility(View.GONE)
            }

            ResponderStatus.PUBLISHING -> {
                //footer
                `$`.id(R.id.responder_publishing_rl)
                        .visible()
                        .id(R.id.responder_to_publish_ll)
                        .visibility(View.GONE)
                        .id(R.id.responder_revoke_btn)
                        .visible()
                        .id(R.id.responder_finish_btn)
                        .visible()
                        .id(R.id.responder_edit_again_btn)
                        .visibility(View.GONE)
                //content
                `$`.id(R.id.responder_to_publish_content_ll)
                        .visibility(View.GONE)
                        .id(R.id.responder_publish_success)
                        .visible()
                        .text(R.string.base_responder_publish_success)
                        .id(R.id.ll_responder_winner_container)
                        .visibility(View.GONE)
                        .id(R.id.rl_layout_group)
                        .visibility(View.GONE)
                        .id(R.id.responder_record_listview)
                        .visibility(View.GONE)
                startFinishTimer()
            }
            ResponderStatus.PUBLISHED -> {
                //footer
                `$`.id(R.id.responder_publishing_rl)
                        .visible()
                        .id(R.id.responder_to_publish_ll)
                        .visibility(View.GONE)
                        .id(R.id.responder_revoke_btn)
                        .visibility(View.GONE)
                        .id(R.id.responder_finish_btn)
                        .visibility(View.GONE)
                        .id(R.id.responder_edit_again_btn)
                        .visible()
                //content
                `$`.id(R.id.responder_to_publish_content_ll)
                        .visibility(View.GONE)
                        .id(R.id.responder_publish_success)
                        .visibility(View.GONE)
                        .id(R.id.ll_responder_winner_container)
                        .visible()
                        .id(R.id.responder_record_listview)
                        .visibility(View.GONE)
                LPRxUtils.dispose(finishTimerDisposable)
                if (TextUtils.isEmpty(winner)) {
                    `$`.id(R.id.responder_publish_success)
                            .visible()
                            .text(R.string.base_responder_nobody_rob)
                            .id(R.id.ll_responder_winner_container)
                            .visibility(View.GONE)
                } else {
                    val winnerTv = `$`.id(R.id.responder_bingo_user_tv).view<TextView>()
                    winnerTv.text = CommonUtils.getEncodePhoneNumber(winner)
                    var groupItem: LPResRoomGroupInfoModel.GroupItem? = null
                    if (userModel != null) {
                        groupItem = showGroupName(userModel)
                    } else {
                        `$`.id(R.id.responder_bingo_group_tv).visibility(View.GONE)
                    }
                    if (!isRecordBack) {
                        var responderRecordModels: MutableList<ResponderRecordModel> = routerListener.getResponderRecord() as MutableList<ResponderRecordModel>
                        val responderRecordModel = ResponderRecordModel()
                        responderRecordModel.userName = winner
                        responderRecordModel.publishCount = routerListener.getLiveRoom()?.onlineUserVM?.studentList?.size
                                ?: 0
                        if (groupItem != null) {
                            responderRecordModel.groupName = groupItem.name
                        }
                        responderRecordModels.add(responderRecordModel)
                        routerListener.setResponderRecord(responderRecordModels)
                    }
                }
                lpUserModel = userModel
            }
            ResponderStatus.RECORD -> {
                `$`.id(R.id.responder_to_publish_content_ll)
                        .visibility(View.GONE)
                        .id(R.id.responder_publish_success)
                        .visibility(View.GONE)
                        .id(R.id.ll_responder_winner_container)
                        .visibility(View.GONE)
                        .id(R.id.responder_record_listview)
                        .visible()
                val responderRecordModels: List<ResponderRecordModel> = routerListener.getResponderRecord()
                responderAdapter.setNewData(responderRecordModels)
            }
        }
        `$`.id(R.id.responder_record_tv).text(if (responderStatus != ResponderStatus.RECORD) getString(R.string.base_responder_review_record) else getString(R.string.base_back))
        val responderRecordModels: List<ResponderRecordModel> = routerListener.getResponderRecord()
        `$`.id(R.id.responder_record_tv).visibility(if (responderRecordModels.isEmpty()) View.GONE else View.VISIBLE)
    }

    private fun startFinishTimer() {
        LPRxUtils.dispose(finishTimerDisposable)
        // 默认自动结束计时 30 秒
        val endTime = 30
        finishTimerDisposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { aLong: Long ->
                    if (aLong >= endTime) {
                        routerListener.getLiveRoom()?.run {
                            toolBoxVM.requestAnswerRacerEnd(false)
                        }
                        `$`.id(R.id.responder_finish_btn).text(R.string.base_responder_finish)
                        LPRxUtils.dispose(finishTimerDisposable)
                    } else {
                        `$`.id(R.id.responder_finish_btn).text(`$`.contentView().context.getString(R.string.base_responder_finish)
                                + "(" + (endTime - aLong) + ")")
                    }
                }
        compositeDisposable.add(finishTimerDisposable!!)
    }

    private fun showGroupName(userModel: LPUserModel): LPResRoomGroupInfoModel.GroupItem? {
        val groupItem = getGroupItem(userModel.groupId)
        return if (groupItem != null && groupItem.id != 0 && groupItem.groupItemModel != null) {
            `$`.id(R.id.winner_group_item).visibility(View.VISIBLE)
            `$`.id(R.id.responder_bingo_group_tv).text(groupItem.groupItemModel.name)
            if (!TextUtils.isEmpty(groupItem.groupItemModel.color)) {
                groupCircleColorView.setColor(Color.parseColor(groupItem.groupItemModel.color))
                groupCircleColorView.visibility = View.VISIBLE
            } else {
                groupCircleColorView.visibility = View.GONE
            }
            groupItem.groupItemModel
        } else {
            `$`.id(R.id.winner_group_item).visibility(View.GONE)
            null
        }
    }

    private fun getGroupItem(groupId: Int): LPGroupItem? {
        val groupList: List<LPGroupItem> = routerListener.getLiveRoom()?.onlineUserVM?.groupList as List<LPGroupItem>
        val size = groupList.size
        for (i in 0 until size) {
            val lpGroupItem = groupList[i]
            if (lpGroupItem.id == groupId) {
                return lpGroupItem
            }
        }
        return null
    }

    enum class ResponderStatus {
        TO_PUBLISH, PUBLISHING, PUBLISHED, RECORD
    }

    internal class ResponderAdapter(context: Context?) : BaseAdapter<ResponderRecordModel>(context, R.layout.uibase_item_responder, null) {

        @SuppressLint("SetTextI18n")
        override fun convert(helper: ViewHolder, item: ResponderRecordModel, position: Int) {
            val tvSerialNumber = helper.getView<TextView>(R.id.tv_serial_number)
            val tvUserName = helper.getView<TextView>(R.id.tv_responder_username)
            val tvGroupName = helper.getView<TextView>(R.id.tv_responder_group_name)
            val tvUserCount = helper.getView<TextView>(R.id.tv_responder_count)
            tvSerialNumber.text = (position + 1).toString()
            tvUserName.text = CommonUtils.getEncodePhoneNumber(item.userName)
            tvUserCount.text = item.publishCount.toString() + "人"
            if (!TextUtils.isEmpty(item.groupName)) {
                tvGroupName.text = item.groupName
                tvGroupName.visibility = View.VISIBLE
                tvUserCount.visibility = View.VISIBLE
            } else {
                tvGroupName.visibility = View.GONE
            }
        }
    }
}